using System.Collections.Generic;
using System.Linq;
using EnvDTE;
using Microsoft.VisualStudio.Shell.Interop;

namespace TellagoInc.VsTagExplorer.TagSelector
{
    public class EditTagsWorker : TagsWorker
    {
        public EditTagsWorker(DTE envDte, SVsSolution solution, TagsSelector selector) : base(envDte, solution, selector)
        {
        }

        protected override IEnumerable<string> GetCandidateStrings(IEnumerable<FileItem> selectedItems)
        {
            var rootProjectItem =  envDte.SelectedItems
                .OfType<SelectedItem>()
                .FirstOrDefault();

            IVsHierarchy hierarchy;

            ((IVsSolution) solution).GetProjectOfUniqueName(rootProjectItem.ProjectItem.ContainingProject.UniqueName, out hierarchy);

            var buildPropertyStorage = hierarchy as IVsBuildPropertyStorage;
            if (buildPropertyStorage != null)
            {
                uint itemId;
                string currentTags;
                var fullPath = (string)rootProjectItem.ProjectItem.Properties.Item("FullPath").Value;
                hierarchy.ParseCanonicalName(fullPath, out itemId);
                buildPropertyStorage.GetItemAttribute(itemId, "Tags", out currentTags);
                if (currentTags != null)
                {
                    return currentTags.Split(' ');
                }
            }

            return new string[0];
        }

        protected override void ApplyTags(string currentTags, string newTags, IVsBuildPropertyStorage buildPropertyStorage, uint itemId)
        {
            buildPropertyStorage.SetItemAttribute(itemId, "Tags", newTags);
        }
    }
}